const ble = require("../../utils/bluetooth");
const util = require("../../utils/util");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    param_list : [
      ["电池物理容量_AH", "", "", false, 4353, 10],
      ["电池实际串数", "", "", false, 4354, 1],
      ["检流电阻_uΩ", "", "", false, 4355, 1],
      ["满充容量_AH", "", "", true, 0, 1],
      ["电池寿命SOH_%", "", "", true, 0, 1],
      ["总放电_AH", "", "", true, 0, 1],
      ["电池规格型号", "", "", true, 0, 1]
    ],
    modify_list : []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (ble.isConncted()) {
      this.readData()
    }
  },

  async readData() {
    let designers = await ble.getDesingerCap(false)

    this.data.param_list[0][1] = designers[0]
    this.data.param_list[1][1] = designers[1]
    this.data.param_list[2][1] = designers[2]
    this.data.param_list[3][1] = app.globalData.battery.full
    this.data.param_list[4][1] = app.globalData.battery.shouming
    this.data.param_list[5][1] = app.globalData.battery.fangdian_total
    this.data.param_list[6][1] = app.globalData.battery.model

    this.setData({
      param_list : this.data.param_list
    })
  },
  
  changeContent(e) {
    const index = e.currentTarget.dataset.index; 
    const value =  e.detail.value;
    this.data.param_list[index][2] = value
    this.addModifyList({
      address : e.currentTarget.dataset.address,
      value : value * e.currentTarget.dataset.ratio
    })
  },

  addModifyList(e) {
    var b_exists = false

    for (let i = 0; i < this.data.modify_list.length; i++) {
      const element = this.data.modify_list[i];
      if (element.address == e.address) {
        element.value = e.value
        b_exists = true
      }
    }

    if (!b_exists) {
      this.data.modify_list.push({
        address : e.address,
        value : e.value
      })
    }
  },

  async save() {
    if (!ble.isConncted()) {
      return;
    }

    wx.showLoading({
      title: '保存中...',
    })
    console.log(this.data.modify_list)

    for (let i = 0; i < this.data.modify_list.length; i++) {
      const element = this.data.modify_list[i];
      let address = element.address
      let value = parseInt(element.value)
      console.log("发送地址：",address, value)
      await ble.writeValueWrapper(address, value)
      await util.sleep(500)
    }

    wx.hideLoading()
  }
})